/**
 * 通用进度通知Hook
 * 提供标准化的进度管理方法，支持任意类型的长时间运行任务
 */

import { useCallback } from 'react';
import { useUniversalNotification } from '../contexts/UniversalNotificationContext';
import {
  NotificationType,
  NotificationStatus,
  ProgressInfo,
  ErrorInfo,
  StatisticsInfo,
  NotificationCallbacks,
  NotificationConfig
} from '../types/notification';

// 进度通知配置
export interface ProgressNotificationConfig extends NotificationConfig {
  showEstimatedTime?: boolean;
  showSpeed?: boolean;
  showStatistics?: boolean;
  enableRetry?: boolean;
  maxRetries?: number;
  retryDelay?: number;
}

// 进度通知选项
export interface ProgressNotificationOptions {
  type?: NotificationType;
  title: string;
  description?: string;
  config?: ProgressNotificationConfig;
  callbacks?: NotificationCallbacks;
  category?: string;
  source?: string;
  target?: string;
  metadata?: Record<string, any>;
}

// 进度更新选项
export interface ProgressUpdateOptions {
  progress?: number | ProgressInfo;
  currentStage?: string;
  currentItem?: string;
  statistics?: StatisticsInfo;
  message?: string;
  estimatedTime?: number;
  speed?: number;
  title?: string;        // 新增：允许更新标题
  description?: string;  // 新增：允许更新描述
}

// 完成选项
export interface CompletionOptions {
  success?: boolean;
  summary?: string;
  statistics?: StatisticsInfo;
  data?: any;
  message?: string;
}

// 错误选项
export interface ErrorOptions extends ErrorInfo {
  retryable?: boolean;
  autoRetry?: boolean;
}

export const useProgressNotification = () => {
  const { add, update, remove } = useUniversalNotification();

  // 开始进度通知
  const start = useCallback((options: ProgressNotificationOptions): string => {
    const {
      type = 'progress',
      title,
      description,
      config = {},
      callbacks,
      category,
      source,
      target,
      metadata
    } = options;

    const defaultConfig: ProgressNotificationConfig = {
      persistent: true,
      autoClose: false,
      showProgress: true,
      showTimestamp: true,
      showEstimatedTime: true,
      showSpeed: false,
      showStatistics: false,
      enableRetry: false,
      maxRetries: 3,
      retryDelay: 1000,
      ...config,
    };

    return add({
      type,
      status: 'running',
      title,
      description,
      progress: 0, // 设置数字进度值
      progressInfo: { // 保留详细进度信息
        current: 0,
        total: 100,
        processed: 0,
        remaining: 100,
        estimatedTime: 0,
      },
      config: defaultConfig,
      callbacks,
      category,
      source,
      target,
      metadata,
    });
  }, [add]);

  // 更新进度
  const updateProgress = useCallback((
    id: string,
    options: ProgressUpdateOptions
  ) => {
    const {
      progress,
      currentStage,
      currentItem,
      statistics,
      message,
      estimatedTime,
      speed,
      title: customTitle,
      description: customDescription
    } = options;

    let progressInfo: ProgressInfo;

    if (typeof progress === 'number') {
      progressInfo = {
        current: Math.max(0, Math.min(100, progress)),
        estimatedTime,
        speed,
      };
    } else if (progress) {
      progressInfo = {
        ...progress,
        current: Math.max(0, Math.min(100, progress.current)),
      };
    } else {
      progressInfo = { current: 0 };
    }

    // 构建标题和描述
    let title = customTitle || currentStage || '处理中';
    let description = customDescription || message;

    if (!description) {
      if (currentStage && currentItem) {
        description = `${currentItem} - ${Math.round(progressInfo.current)}%`;
        if (progressInfo.processed && progressInfo.total) {
          description = `${currentItem} (${progressInfo.processed}/${progressInfo.total}) - ${Math.round(progressInfo.current)}%`;
        }
      } else if (currentStage) {
        description = `${currentStage} - ${Math.round(progressInfo.current)}%`;
        if (progressInfo.processed && progressInfo.total) {
          description = `${progressInfo.processed}/${progressInfo.total} - ${Math.round(progressInfo.current)}%`;
        }
      } else if (currentItem) {
        description = `${currentItem} - ${Math.round(progressInfo.current)}%`;
      } else {
        description = `进度 ${Math.round(progressInfo.current)}%`;
      }

      // 添加预计剩余时间
      if (progressInfo.estimatedTime && progressInfo.estimatedTime > 0) {
        const minutes = Math.floor(progressInfo.estimatedTime / 60);
        const seconds = Math.floor(progressInfo.estimatedTime % 60);
        const timeText = minutes > 0 ? `${minutes}分${seconds}秒` : `${seconds}秒`;
        description += ` (预计剩余: ${timeText})`;
      }

      // 添加处理速度
      if (progressInfo.speed && progressInfo.speed > 0) {
        description += ` (${progressInfo.speed.toFixed(1)}/s)`;
      }
    }

    update(id, {
      title,
      description,
      progress: progressInfo.current, // 设置数字进度值供Dynamic Island使用
      progressInfo, // 保留详细进度信息对象
      statistics,
      lastUpdate: Date.now(),
    });
  }, [update]);

  // 暂停进度
  const pause = useCallback((
    id: string,
    currentProgress?: number,
    currentStage?: string
  ) => {
    update(id, {
      title: '已暂停',
      status: 'paused',
      description: currentStage ? `${currentStage} - 已暂停` : '任务已暂停',
      progress: currentProgress, // 设置数字进度值
      progressInfo: currentProgress ? { current: currentProgress } : undefined, // 保留详细进度信息
      lastUpdate: Date.now(),
    });
  }, [update]);

  // 恢复进度
  const resume = useCallback((
    id: string,
    currentProgress?: number,
    currentStage?: string
  ) => {
    update(id, {
      title: currentStage || '继续处理',
      status: 'running',
      description: currentStage ? `${currentStage} - 继续处理` : '任务已恢复',
      progress: currentProgress, // 设置数字进度值
      progressInfo: currentProgress ? { current: currentProgress } : undefined, // 保留详细进度信息
      lastUpdate: Date.now(),
    });
  }, [update]);

  // 取消进度
  const cancel = useCallback((
    id: string,
    reason?: string
  ) => {
    update(id, {
      title: '已取消',
      status: 'cancelled',
      description: reason || '任务已被取消',
      progress: { current: 0 },
      lastUpdate: Date.now(),
    });

    // 5秒后自动移除
    setTimeout(() => {
      remove(id);
    }, 5000);
  }, [update, remove]);

  // 完成进度
  const complete = useCallback((
    id: string,
    options: CompletionOptions = {}
  ) => {
    const {
      success = true,
      summary,
      statistics,
      data,
      message
    } = options;

    let title = success ? '完成' : '失败';
    let description = message || summary;

    if (!description) {
      if (success && statistics) {
        // 构建统计信息描述
        const stats = Object.entries(statistics)
          .map(([key, value]) => `${key}: ${value}`)
          .join(', ');
        description = stats;
      } else {
        description = success ? '任务已成功完成' : '任务执行失败';
      }
    }

    const finalStatus = success ? 'success' : 'failed';

    update(id, {
      title,
      status: finalStatus,
      progress: 100, // 设置数字进度值
      progressInfo: { current: 100 }, // 保留详细进度信息
      description,
      statistics,
      data,
      endTime: Date.now(),
      lastUpdate: Date.now(),
    });

    // 根据通知类型决定自动移除策略
    if (success) {
      // 对于同步任务，成功后30秒自动移除；其他类型10秒后移除
      const autoRemoveDelay = (data?.category === 'data-sync' || data?.type === 'sync') ? 30000 : 10000;

      setTimeout(() => {
        remove(id);
      }, autoRemoveDelay);
    }
  }, [update, remove]);

  // 失败处理
  const fail = useCallback((
    id: string,
    error: ErrorOptions
  ) => {
    const {
      message,
      details,
      code,
      retryable = false,
      autoRetry = false,
      retryCount = 0,
      maxRetries = 3
    } = error;

    let title = '执行失败';
    let description = message;

    if (code) {
      title = `失败 (${code})`;
    }

    if (retryable && retryCount < maxRetries) {
      title = `失败 - 重试中 (${retryCount + 1}/${maxRetries})`;
      description = `${message} - 正在重试...`;
    }

    update(id, {
      title,
      status: retryable && retryCount < maxRetries ? 'retrying' : 'failed',
      description,
      error: {
        message,
        details,
        code,
        retryable,
        retryCount,
        maxRetries,
      },
      lastUpdate: Date.now(),
    });

    // 如果启用自动重试
    if (autoRetry && retryable && retryCount < maxRetries) {
      setTimeout(() => {
        update(id, {
          status: 'running',
          title: '重试中',
          description: `正在进行第 ${retryCount + 1} 次重试...`,
          error: {
            ...error,
            retryCount: retryCount + 1,
          },
          lastUpdate: Date.now(),
        });
      }, error.retryDelay || 1000);
    }
  }, [update]);

  // 重试
  const retry = useCallback((
    id: string,
    retryCount: number = 0
  ) => {
    update(id, {
      status: 'running',
      title: '重试中',
      description: `正在进行第 ${retryCount + 1} 次重试...`,
      progress: { current: 0 },
      error: undefined,
      lastUpdate: Date.now(),
    });
  }, [update]);

  // 设置状态
  const setStatus = useCallback((
    id: string,
    status: NotificationStatus,
    message?: string
  ) => {
    const statusTitles: Record<NotificationStatus, string> = {
      idle: '空闲',
      running: '运行中',
      success: '成功',
      error: '错误',
      warning: '警告',
      paused: '已暂停',
      cancelled: '已取消',
      completed: '已完成',
      failed: '失败',
      pending: '等待中',
      retrying: '重试中',
    };

    update(id, {
      status,
      title: statusTitles[status],
      description: message,
      lastUpdate: Date.now(),
    });
  }, [update]);

  return {
    start,
    updateProgress,
    pause,
    resume,
    cancel,
    complete,
    fail,
    retry,
    setStatus,
    remove,
  };
};
